<?php

namespace Admin\Controllers;

use Models\Documents;
use Forms\DocForm;
use Models\Topics;
use Models\Doctypes;
use Forms\UploadForm;
use \COM;
use Forms\SearchForm;

class DocController extends ControllerBase {

    public function alldocAction() {
        $form = new SearchForm();
        $currentPage = (int) $this->request->getPost('page');
        if (!$currentPage) {
            $currentPage = 1;
        }
        $limit = (int) $this->request->getPost('limit');
        if (!$limit) {
            $limit = 10;
        }
        $query = $this->modelsManager->createBuilder()
                ->columns(array(
                    'Models\Documents.id',
                    'Models\Documents.title',
                    'Models\Documents.topic_id',
                    'Models\Documents.description',
                    'Models\Documents.submit_date',
                    'Models\Documents.cost',
                    'Models\Documents.link',
                    'Models\Documents.public',
                    'Models\Documents.image',
                    'Models\Documents.download',
                    'Models\Documents.discount',
                    'Topics.name TopicName',
                    'Doctypes.name TypeName',
                    'Users.username UploadUser',
                ))
                ->from('Models\Documents')
                ->leftjoin('Models\Topics', 'Topics.id = Models\Documents.topic_id', 'Topics')
                ->leftjoin('Models\Doctypes', 'Doctypes.id = Topics.doctype_id', 'Doctypes')
                ->leftjoin('Models\Users', 'Models\Documents.uploadby = Users.id', 'Users')
                ->orderby('Models\Documents.submit_date DESC')
                ->where('1=1');
        if ($this->request->getPost('doctype')) {
            $query->andwhere('Topics.doctype_id = \'' . ($this->request->getPost('doctype')) . '\'');
        }
        if ($this->request->getPost('topic')) {
            $query->andwhere('Topics.id = \'' . ($this->request->getPost('topic')) . '\'');
        }
        if ($this->request->getPost('text')) {
            $query->andwhere('Models\Documents.title LIKE \'%' . ($this->request->getPost('text')) . '%\'');
        }

        $docs = $query->getQuery()->execute();

        $pagination = new \Phalcon\Paginator\Adapter\Model(array(
            "data" => $docs,
            "limit" => $limit,
            "page" => $currentPage
        ));
        $this->view->docs = $pagination->getPaginate();
        $this->view->form = $form;
    }

    public function addAction() {
        $identify = $this->auth->getIdentity();
        $form = new UploadForm();
        $support_files = array('doc', 'docx', 'pdf', 'ppt', 'pptx', 'txt');

        if ($this->request->isPost()) {
            if ($this->request->getPost('doctype')) {
                $form = new UploadForm((object) ['doctype' => $this->request->getPost('doctype')]);
            }
            $request = $this->request->getPost();
            if ($_FILES["file"]) {
                $request['file'] = $_FILES["file"]["name"];
            }
            if ($_FILES["image"]) {
                $request['image'] = $_FILES["image"]["name"];
            }

            if ($form->isValid($request)) {
                if (!$_FILES["file"]["error"]) {
                    $pathinfo = pathinfo($_FILES["file"]["name"]);
                    $extension = $pathinfo['extension'];
                    if (in_array($extension, $support_files)) {
                        $doc = new Documents();
                        $doc->assign(array(
                            'doctype_id' => $request['doctype'],
                            'topic_id' => $request['topic'],
                            'title' => $request['title'],
                            'link' => $request['file'],
                            'cost' => $request['cost'],
                            'description' => $request['description'],
                            'uploadby' => $identify['id'],
                            'submit_date' => date('Y-m-d H:i:s'),
                            'image' => '',
                            'discount' => 0,
                            'download' => 0,
                            'public' => 0,
                        ));
                        if ($doc->save()) {
                            $upload_dir = UPLOAD_DIR . $request['doctype'] . '/' . $request['topic'] . '/' . $doc->id . '/';
                            $review_dir = REVIEW_DIR . '/' . $request['topic'] . '/' . $doc->id . '/';
                            if (!file_exists($upload_dir)) {
                                mkdir($upload_dir, 0777, true);
                            }
                            if (!file_exists($review_dir)) {
                                mkdir($review_dir, 0777, true);
                            }
                            if (in_array($extension, array('doc', 'docx', 'txt'))) {
                                try {
                                    $word = new COM("Word.Application") or die("Could not initialise Object.");
                                    // set it to 1 to see the MS Word window (the actual opening of the document)
                                    $word->Visible = 0;
                                    // recommend to set to 0, disables alerts like "Do you want MS Word to be the default .. etc"
                                    $word->DisplayAlerts = 0;
                                    // open the word 2007-2013 document 
                                    $word->Documents->Open($_FILES["file"]["tmp_name"]);
                                    // convert word 2007-2013 to PDF
                                    $word->ActiveDocument->ExportAsFixedFormat($review_dir . $_FILES["file"]["name"] . '.pdf', 17, false, 0, 0, 0, 0, 7, true, true, 2, true, true, false);
                                    // quit the Word process
                                    $word->Quit(false);
                                    // clean up
                                    unset($word);
                                    require_once('../app/library/pdf/fpdf.php');
                                    require_once('../app/library/pdf/fpdi.php');

                                    $pdf = new \FPDI();

                                    $pdf->AddPage();
                                    $pdf->setSourceFile($review_dir . $_FILES["file"]["name"] . '.pdf');

                                    $tplidx = $pdf->importPage(1);
                                    for ($i = 1; $i <= 6; $i++) {
                                        $tplidx = $pdf->ImportPage($i);
                                        $pdf->useTemplate($tplidx, 10, 10, 200);
                                        $pdf->AddPage();
                                    }
                                    $pdf->Output($review_dir . $_FILES["file"]['name'] . '.pdf');
                                    $doc->review = $_FILES["file"]["name"] . '.pdf';
                                } catch (\Exception $e) {
                                    $doc->review = '';
                                    $form->appendMessage("Không thể tạo file xem trước", "add_doc", null);
                                }
                            }
                            if ($extension == 'pdf') {
                                try {
                                    require_once('../app/library/pdf/fpdf.php');
                                    require_once('../app/library/pdf/fpdi.php');

                                    $pdf = new \FPDI();

                                    $pdf->AddPage();
                                    $pdf->setSourceFile($_FILES["file"]['tmp_name']);

                                    $tplidx = $pdf->importPage(1);
                                    for ($i = 1; $i <= 6; $i++) {
                                        $tplidx = $pdf->ImportPage($i);
                                        $pdf->useTemplate($tplidx, 10, 10, 200);
                                        $pdf->AddPage();
                                    }
                                    $pdf->Output($review_dir . $_FILES["file"]['name']);
                                    $doc->review = $_FILES["file"]["name"];
                                } catch (\Exception $e) {
                                    $doc->review = '';
                                    $form->appendMessage("Không thể tạo file xem trước", "add_doc", null);
                                }
                            }
                            move_uploaded_file($_FILES["file"]["tmp_name"], $upload_dir . $_FILES["file"]["name"]);

                            // Upload image
                            if (!$_FILES['image']['error']) {
                                move_uploaded_file($_FILES["image"]["tmp_name"], $review_dir . $_FILES["image"]["name"]);
                                $doc->image = $_FILES["image"]["name"];
                            }
                            $doc->save();
                            $form->appendMessage("Upload file thành công", "add_doc", null);
                        } else {
                            foreach ($doc->getMessages() as $value) {
                                $form->appendMessage($value, "upload_info", null);
                            }
                        }
                    } else {

                        $form->appendMessage("Định dạng file không hỗ trợ", "add_doc", null);
                    }
                } else {
                    $form->appendMessage("Fail to Upload File", "add_doc", null);
                }
            }
        }
        $this->view->form = $form;
    }

    public function uploadAction() {
        $form = new SearchForm();
        $currentPage = $this->request->getPost('page');
        if (!$currentPage) {
            $currentPage = 1;
        }
        $limit = (int) $this->request->getPost('limit');
        if (!$limit) {
            $limit = 10;
        }
        $query = $this->modelsManager->createBuilder()
                ->columns(array(
                    'Models\Documents.id',
                    'Models\Documents.topic_id',
                    'Models\Documents.title',
                    'Models\Documents.description',
                    'Models\Documents.submit_date',
                    'Models\Documents.cost',
                    'Models\Documents.link',
                    'Models\Documents.public',
                    'Models\Documents.image',
                    'Models\Documents.download',
                    'Models\Documents.discount',
                    'Topics.name TopicName',
                    'Doctypes.name TypeName',
                    'Users.username UploadUser',
                ))
                ->from('Models\Documents')
                ->leftjoin('Models\Topics', 'Topics.id = Models\Documents.topic_id', 'Topics')
                ->leftjoin('Models\Doctypes', 'Doctypes.id = Topics.doctype_id', 'Doctypes')
                ->leftjoin('Models\Users', 'Models\Documents.uploadby = Users.id', 'Users')
                ->where('Models\Documents.public = 0')
                ->orderby('Models\Documents.submit_date DESC');
        if ($this->request->getPost('doctype')) {
            $query->andwhere('Topics.doctype_id = \'' . ($this->request->getPost('doctype')) . '\'');
        }
        if ($this->request->getPost('topic')) {
            $query->andwhere('Topics.id = \'' . ($this->request->getPost('topic')) . '\'');
        }
        if ($this->request->getPost('text')) {
            $query->andwhere('Models\Documents.title LIKE \'%' . ($this->request->getPost('text')) . '%\'');
        }

        $docs = $query->getQuery()->execute();

        $pagination = new \Phalcon\Paginator\Adapter\Model(
                array(
            "data" => $docs,
            "limit" => $limit,
            "page" => $currentPage
                )
        );
        $this->view->docs = $pagination->getPaginate();
        $this->view->form = $form;
    }

    public function editAction() {
        $identity = $this->auth->getIdentity();
        $form = new DocForm();
        $id = $this->dispatcher->getParam("id");
        $doc = Documents::findFirstById($id);
        if ($doc) {
            $type_id = $doc->doctype_id;
            $topic_id = $doc->topic_id;
            $form = new DocForm($doc);
            if ($this->request->isPost()) {
                $request = $this->request->getPost();
                if ($form->isValid($request)) {
                    $doc->assign(array(
                        'title' => $request['title'],
                        'doctype_id' => $request['doctype_id'],
                        'topic_id' => $request['topic_id'],
                        'description' => $request['description'],
                        'submit_date' => $request['submitdate'],
                        'cost' => $request['cost'],
                        'link' => $request['link'],
                        //                        'image' => $request['image'],
                        'download' => $request['download'],
                        //                        'discount' => $request['discount'],
                        'updateby' => $identity['id'],
                        'updatetime' => date('Y-m-d H:i:s'),
                        'public' => $request['public'],
                    ));
                    // Upload image
                    if (!$_FILES['image']['error']) {
                        $review_dir = REVIEW_DIR . '/' . $request['topic_id'] . '/' . $doc->id . '/';
                        if (!file_exists($review_dir)) {
                            mkdir($review_dir, 0777, true);
                        }
                        move_uploaded_file($_FILES["image"]["tmp_name"], $review_dir . $_FILES["image"]["name"]);
                        $doc->image = $_FILES["image"]["name"];
                    }
                    if ($doc->save()) {
                        $form->appendMessage("Cập nhật thành công", "edit_doc", null);
                        /* $this->flash->success('Cập nhật thành công!'); */
                    }
                    foreach ($doc->getMessages() as $value) {
                        $form->appendMessage($value, "edit_doc", null);
                    }
                    /* $this->flash->error($doc->getMessages()); */
                }
            }
            $this->view->doc = $doc;
            $this->view->form = $form;
        } else {
            $this->dispatcher->forward(array(
                'module' => 'admin',
                'controller' => 'error',
                'action' => 'notAvailable'
            ));
        }
    }

    public function deleteAction() {
        $ids = $this->request->getPost('ids');
        if ($ids) {
            $ids_str = implode(',', $ids);
            $docs = Documents::find("id IN ($ids_str)");
            foreach ($docs as $doc) {
                $topic = Topics::findFirstById($doc->topic_id);
                $dir = UPLOAD_DIR . $topic->doctype_id . '/' . $doc->topic_id . '/' . $doc->id;
                $dir_ = REVIEW_DIR . $doc->topic_id . '/' . $doc->id;
                $this->deleteDir($dir);
                $this->deleteDir($dir_);
                if (!$doc->delete()) {
                    echo "Cannot delete document $doc->id<br>";
                }
            }
        }
        $this->view->disable();
    }

    public function publicAction() {
        $ids = $this->request->getPost('ids');
        if ($ids) {
            $ids_str = implode(',', $ids);
            $docs = Documents::find("id IN ($ids_str)");
            foreach ($docs as $doc) {
                $doc->public = 1;
                if (!$doc->save()) {
                    echo "Cannot public document $doc->id<br>";
                } else {
                    $type = Doctypes::findFirstById($doc->doctype_id);
                    $user = \Models\Users::findFirstById($doc->uploadby);
                    if ($type && $user) {
                        $user->points += $type->points;
                        $user->save();
                    }
                }
            }
        }
        $this->view->disable();
    }

    public function blockAction() {
        $ids = $this->request->getPost('ids');
        if ($ids) {
            $ids_str = implode(',', $ids);
            $docs = Documents::find("id IN ($ids_str)");
            foreach ($docs as $doc) {
                $doc->public = -1;
                if (!$doc->save()) {
                    echo "Cannot block document $doc->id<br>";
                }
            }
        }
        $this->view->disable();
    }

    private function deleteDir($dirPath) {
        if (is_dir($dirPath)) {
            $objects = scandir($dirPath);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($dirPath . DIRECTORY_SEPARATOR . $object) == "dir") {
                        deleteDirectory($dirPath . DIRECTORY_SEPARATOR . $object);
                    } else {
                        unlink($dirPath . DIRECTORY_SEPARATOR . $object);
                    }
                }
            }
            reset($objects);
            rmdir($dirPath);
        }
    }

}
